package com.es.controller;

import java.text.MessageFormat;

import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.MissingResourceException;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;


public class BaseController {
	
	private static final  Logger log = Logger.getLogger(BaseController.class);
	
	protected static ClassLoader getCurrentClassLoader(Object defaultObject){
		
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		
			if(loader == null){
				loader = defaultObject.getClass().getClassLoader();
			}
		
		return loader;
	}
	
	@SuppressWarnings("unchecked")
	public static Object getFacesContextManagedBean(String managedBeanName,Class beanClass) {
		
		try {
			FacesContext ctx = FacesContext.getCurrentInstance();
			Application app = ctx.getApplication();
			ExpressionFactory expressionFactory = app.getExpressionFactory();
			ELContext elContext = ctx.getELContext();
			ValueExpression valueExpression;
			
				if (managedBeanName.indexOf('#') == -1){
					managedBeanName = "#{" + managedBeanName + "}";
					valueExpression = expressionFactory.createValueExpression(elContext, managedBeanName, beanClass);
				}else{
					valueExpression = expressionFactory.createValueExpression(elContext, managedBeanName , beanClass);
				}
			return valueExpression.getValue(elContext);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public static boolean setFacesContextManagedBean(String managedBeanName,Object managedBean,Class beanClass) {
		
		try {
			FacesContext ctx = FacesContext.getCurrentInstance();
			Application app = ctx.getApplication();
			ExpressionFactory expressionFactory = app.getExpressionFactory();
			ELContext elContext = ctx.getELContext();
			ValueExpression valueExpression;
			
				if (managedBeanName.indexOf('#') == -1){
					managedBeanName = "#{" + managedBeanName + "}";
					valueExpression = expressionFactory.createValueExpression(elContext, managedBeanName, beanClass);
				}else{
					valueExpression = expressionFactory.createValueExpression(elContext, managedBeanName , beanClass);
				}
				
			valueExpression.setValue(elContext,managedBean);
			return true;
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			return false;
		}
	}
	
	public static String getMessageResourceString(String bundleName,String key,Object params[],Locale locale){
		
		ResourceBundle bundle;
		String text = null;
		
			if(locale == null){
				bundle = ResourceBundle.getBundle(bundleName);
			}else{
				bundle = ResourceBundle.getBundle(bundleName, locale,getCurrentClassLoader(params));  //?
			}

			try{
				text = bundle.getString(key);
			} catch(MissingResourceException e){
				text = "?? key " + key + " not found ??";
			}

			if(params != null){
				MessageFormat mf = new MessageFormat(text, locale);
				text = mf.format(params, new StringBuffer(), null).toString();
			}

		return text;
	}
	
	public static String getMessageResourceString(String bundleName,String key,Object params[]){
		
		ResourceBundle bundle;
		String text = null;
		Locale locale = getRequestFromFacesContext().getLocale();
		
			if(locale == null){
				bundle = ResourceBundle.getBundle(bundleName);
			}else{
				bundle = ResourceBundle.getBundle(bundleName, locale,getCurrentClassLoader(params));  //?
			}

			try{
				text = bundle.getString(key);
			} catch(MissingResourceException e){
				text = "?? key " + key + " not found ??";
			}

			if(params != null){
				MessageFormat mf = new MessageFormat(text, locale);
				text = mf.format(params, new StringBuffer(), null).toString();
			}

		return text;
	}

	public static void addGlobalFacesMessage(FacesContext fc,String errMsg,String clientId,Severity severity ){
		
		/*FacesMessage(FacesMessage.Severity severity, java.lang.String summary, java.lang.String detail)*/ 
		FacesMessage facesMessage = new FacesMessage(severity, errMsg, null);
		fc.addMessage(clientId, facesMessage);
		
	}
	
	public static void saveToCookie(HttpServletResponse response, Object cookieName, Object cookieValue){
		Cookie cookie = new Cookie(cookieName.toString(), cookieValue.toString());
		response.addCookie(cookie);
	}
	
	public static String getCookieValue(HttpServletRequest request,String cookieName){
		Cookie[] cookies = request.getCookies();
			if(cookies == null){
				return null;
			}
			
		Cookie cookie;
		for(int i=0;i<cookies.length;i++){
			cookie = cookies[i];
			if(cookie.getName().equals(cookieName)){
				return cookie.getValue();
			}
		}
					
		return null;
	}
	
	public static void removeCookie(HttpServletResponse response, Object cookieName) {
		Cookie cookie = new Cookie(cookieName.toString(), null);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
	
	public static HttpServletRequest getRequestFromFacesContext(){
		FacesContext fc = FacesContext.getCurrentInstance();
		return (HttpServletRequest)fc.getExternalContext().getRequest();
	}
	
	public static HttpSession getSessionFromFacesContext(){
		return (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	}
	
	public static HttpServletResponse getResponceFromFacesContext(){
		FacesContext fc = FacesContext.getCurrentInstance();
		return (HttpServletResponse)fc.getExternalContext().getResponse();
	}
	
	
	public static String getParamValueFromRequest(String paramName){
	     HttpServletRequest request=getRequestFromFacesContext();
	     Map<String, String[]> paramMap=request.getParameterMap();
	     
	     String param[]=paramMap.get(paramName);
	     if(param.length>0){
	     return param[0];
	     }else{
	    	 return null;
	     }
	     
	     
	}

}
